<?php
function unixtime() {
    $data = "[]";
    return _call_erlang('net_web_handler_tpl', 'unixtime', $data);
}


/**
 * @param string $mod 模块
 * @param string $fun 函数
 * @param string $args 参数
 * @return array 结果
 */
function _call_erlang($mod, $fun, $args) {
    $time = time();
    $sign0 = md5($args . '_' . $time . '_' . 'c613db28b416ddb51b24f95bc0ce8fa7');
    $sign = "<<" . _string_binary($sign0) . ">>";

    $data = "{{$mod},{$fun},{$args},{$time},{$sign}}";

    $body = curlPost('http://127.0.0.1:8889/web', ['call_data' => $data]);
    return json_decode($body, true);
}


function curlPost($url, $postData = [], $headers = []) {
    // 初始化 cURL
    $ch = curl_init();

    // 设置 cURL 选项
    curl_setopt($ch, CURLOPT_URL, $url); // 设置请求的 URL
    curl_setopt($ch, CURLOPT_POST, true); // 设置为 POST 请求
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postData)); // 设置 POST 数据
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); // 返回响应而不是直接输出
    curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); // 设置请求头

    // 执行 cURL 请求并获取响应
    $response = curl_exec($ch);

    // 检查是否有错误发生
    if (curl_errno($ch)) {
        throw new Exception('cURL 请求出错: ' . curl_error($ch));
    }

    // 获取 HTTP 状态码
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

    // 关闭 cURL 资源
    curl_close($ch);

    return $response;
}

function _string_binary($string) {
    $i = 0;
    $number	= [];
    while (isset($string{$i})) {
        $number[] = ord($string[$i]);
        $i++;
    }
    return implode(',', $number);
}


print_r(unixtime());
